package com.mhb.generator.util;

import lombok.Data;
import lombok.experimental.Accessors;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * jdbc 工具类
 *
 * @author 博博
 * @Title: JdbcUtil
 * @time 2019/12/27 0027 16:09
 */
public class JdbcUtil {

    /**
     * 查询操作
     *
     * @param sql    sql语句
     * @param params 参数数组
     * @return 查询结果集
     */
    public static JdbcConn executeQuery(Connection conn, String sql, Object... params) {
        PreparedStatement ps = null;
        ResultSet rs = null;
        JdbcConn jdbcConn = null;
        try {
            // 获取连接
            ps = conn.prepareStatement(sql);
            // 循环塞入值
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            // 执行查询
            rs = ps.executeQuery();
            jdbcConn = new JdbcConn().setConn(conn).setPs(ps).setRs(rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return jdbcConn;
    }

    public static void close(JdbcConn jdbcConn) {
        // 若ResultSet对象不为空，则关闭
        try {
            if (jdbcConn.getRs() != null && !jdbcConn.getRs().isClosed())
                jdbcConn.getRs().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 若Statement对象不为空，则关闭
        try {
            if (jdbcConn.getPs() != null && !jdbcConn.getPs().isClosed())
                jdbcConn.getPs().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 若数据库连接对象不为空，则关闭
        try {
            if (jdbcConn.getConn() != null && !jdbcConn.getConn().isClosed())
                jdbcConn.getConn().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Data
    @Accessors(chain = true)
    public static class JdbcConn {
        private PreparedStatement ps;
        private ResultSet rs;
        private Connection conn;
    }

}
